package com.hfb.mashibing.alip8.designpattern._08ChainOfResponsibility;

import java.util.LinkedList;
import java.util.List;

/**
 * 责任链：
 *  处理 request(1->2->3) V1
 *  处理 response(1->2->3) V2
 */

public class Servlet_MainV2 {
    public static void main(String[] args) {
        Request request = new Request();
        request.str = "大家好：）<script>欢迎👏🏻访问 http://mashibing.com 大家都是 996 ";

        Response response = new Response();
        response.str = "response";

        FilterChain chain = new FilterChain();
        chain.add(new HTMLFilter())
             .add(new SensitiveFilter());
        chain.doFilter(request, response);

        System.err.printf("request:%s\n", request.str);
        System.err.printf("response:%s\n", response.str);
    }


    interface Filter {
        boolean doFilter(Request request, Response response);
    }
    static class FilterChain implements Filter {
        List<Filter> filters = new LinkedList<>();
        FilterChain add(Filter filter){
            filters.add(filter);
            return this;
        }
        @Override
        public boolean doFilter(Request request, Response response) {
            for (Filter filter : filters) {
                filter.doFilter(request, response);
            }
            return true;
        }
    }
    static class HTMLFilter implements Filter{
        @Override
        public boolean doFilter(Request request, Response response) {
            System.out.println("HTMLFilter");
            request.str = request.str.replaceAll("<", "[")
                                     .replaceAll(">", "]");
            response.str += "--HTMLFilter \t";
            return true;
        }
    }
    static class SensitiveFilter implements Filter{
        @Override
        public boolean doFilter(Request request, Response response) {
            System.out.println("SensitiveFilter");
            request.str = request.str.replaceAll("996","995");
            response.str += "--SensitiveFilter\t";
            return true;
        }
    }
    static class Request {
        String str;
    }
    static class Response {
        String str;
    }
}
